package com.mall.web.control.app.pay;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipayNotify;
import com.alipay.util.AlipaySubmit;
import com.mall.biz.pay.PayBizImpl;
import com.mall.client.mall.MallService;
import com.mall.client.mallGroupBuy.MallGroupbBuyService;
import com.mall.client.trade.TradeService;
import com.mall.common.Consts.tradeOrderStatus;
import com.mall.common.Consts.tradeOrderType;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.constant.PropertiesKey;
import com.mall.pojo.Mall;
import com.mall.pojo.MallGroupBuy;
import com.mall.pojo.Trade;
import com.mall.web.control.app.result.MallResultController;

/**
 * 支付宝支付
 * 
 * @author lihaiyang
 *
 */
@Controller
@RequestMapping("/aliPay/")
public class AliPayController implements InitializingBean {

private static final Logger log = LoggerFactory.getLogger(AliPayController.class);
	
	
	/**
	 * 服务器异步通知页面路径
	 */
	private static String NOTIFY_URL;
	
	/**
	 * 付款成功后跳转回的页面路径
	 */
	private static String RETURN_URL;
	/**
	 * 支付方式（不能修改）
	 */
	private static final String PAYMENT_TYPE = "1";
	/**
	 * 支付服务接口名
	 */
	private static String PAY_SERVICE = "alipay.wap.create.direct.pay.by.user";

	
	@Autowired
	private PayBizImpl payBizImpl;
	@Autowired
	private TradeService tradeService;
	@Autowired
	private MallService mallService;
	@Autowired
	private MallGroupbBuyService mallGroupBuyService;
	@Autowired
	private PropertiesConfigure propertiesConfigure;


	@RequestMapping("pay")
	public void pay(@RequestParam(required = true) Long orderId, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) throws Exception {
		Trade trade = tradeService.getTradeByOrderId(orderId);
		if (trade == null) {
			log.error("订单[{}]不存在", orderId);
			return;
		}
		int status = trade.getStatus();
		if (status != tradeOrderStatus.STATUS_NOTPAY) {
			log.error("订单[{}]已经支付，或者订单号失效", orderId);
			return;
		}

		// 超时时间
		String it_b_pay = "";
		// 选填
		// 钱包token
		String extern_token = "";
		// 选填
		String subject = "";
		String show_url = "";
		if(trade.getMallId()!=null && trade.getMallId()>=0){
			if(trade.getType()==5){
				MallGroupBuy mallGroupBuy = this.mallGroupBuyService.getMallGroupBuyById(trade.getParentId());
				if (mallGroupBuy == null) {
					return;
				}
				subject = "购买" + mallGroupBuy.getTitle();
				show_url = propertiesConfigure.getProperties(PropertiesKey.httpbeginurl)+"/mall/malldetail.htm?mallId=" + mallGroupBuy.getMallId();
			}else{
				Mall mall = this.mallService.getMallById(trade.getMallId());
				if (mall == null) {
					return;
				}
				subject = "购买" + mall.getMallName();
				show_url = propertiesConfigure.getProperties(PropertiesKey.httpbeginurl)+"/mall/malldetail.htm?mallId=" + mall.getId();
			}
			
		}else{
			subject = "交易失败";
			return;
		}
		
		// 付款金额 (必填)

		// 测试用，设置付款金额为1分
		// trade.setPrice(trade.getPrice());
		//
		// trade.setPrice(1l);


		String totalFree = String.valueOf(trade.getPrice().doubleValue() / 100);//交易金额
		// 订单描述(必填)
		// String body = "测试商品描述";
		String body = subject;
		// 把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", PAY_SERVICE);
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("seller_id", AlipayConfig.seller_id);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", PAYMENT_TYPE);
		sParaTemp.put("notify_url", NOTIFY_URL);
		sParaTemp.put("return_url", RETURN_URL);

		sParaTemp.put("out_trade_no", trade.getOutTradeNo());
		sParaTemp.put("subject", subject);
		sParaTemp.put("total_fee", totalFree);
		sParaTemp.put("show_url", show_url);
		sParaTemp.put("body", body);
		sParaTemp.put("it_b_pay", it_b_pay);
		sParaTemp.put("extern_token", extern_token);
		
		
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "get", "确认");
		response.setContentType("text/html; charset=UTF-8");
		String fullHtmlText = "<html>" + sHtmlText + "</html>";
		response.getWriter().write(fullHtmlText);
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	
	
	


	
	

	/**
	 * 支付完成后支付宝异步通知接口
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("notify_url")
	public void notify_url(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
			throws IOException {
		log.info("notify_url收到支付宝支付异步通知...");
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map<?, ?> requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
			params.put(name, valueStr);
		}

		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		if (AlipayNotify.verify(params)) {// 验证成功
			log.info("notify_url校验请求成功");
			Date currentTime = new Date();
			Trade trade = tradeService.getByOrderNO(out_trade_no);

			do {
				if (trade == null) {
					log.error("没查询到充值订单[{}]", out_trade_no);
					break;
				}
				if (trade.getStatus() != tradeOrderStatus.STATUS_NOTPAY) {
					log.error("订单状态不是未支付的，订单当前状态未[{}]", trade.getStatus());
					break;
				}
				if (trade_status.equals("TRADE_FINISHED")) {
					// 判断该笔订单是否在商户网站中已经做过处理
					// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					// 如果有做过处理，不执行商户的业务程序
					// 注意：
					// 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
					// 这里先不用做处理。
				} else if (trade_status.equals("TRADE_SUCCESS")) { // 支付成功
					// Trade updateTrade = new Trade();
					// updateTrade.setStatus(tradeOrderStatus.STATUS_PAYSUCCESS);
					// updateTrade.setGmtModify(currentTime);
					// updateTrade.setTradeNo(trade_no);
					trade.setStatus(tradeOrderStatus.STATUS_PAYSUCCESS);
					trade.setGmtModify(currentTime);
					trade.setTradeNo(trade_no);
					boolean success = tradeService.updateById(trade.getId(), trade);

					if (success) {
						log.info("notify_url更新订单状态成功");
						payBizImpl.paySuccessCallback(trade.getId());
						log.info("notify_url更新订单状态成功ok");
					} else {
						log.error("更新订单状态失败");
					}
				}
			} while (false);
			response.getWriter().println("success");
		} else {// 验证失败
			log.info("notify_url校验请求失败");
			response.getWriter().println("fail");
		}
	}

	/**
	 * 支付完成后跳转回的页面地址
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("return_url")
	public String return_url(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
			throws IOException {
		log.info("return_url收到回调");
		// 获取支付宝GET过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}

		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 商户订单号

		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

		// 计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(params);

		if (verify_result) {// 验证成功
			log.info("return_url参数校验成功");
			Trade trade = tradeService.getByOrderNO(out_trade_no);
			if (trade == null) {
				log.error("没查询到充值订单[{}]", out_trade_no);
				return null; // TODO 跳转到error页
			}

			// ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
				Mall mall = this.mallService.getMallById(trade.getMallId());
				String mallName = "";
				try {
					mallName = URLEncoder.encode(mall.getMallName(), MallResultController.UTF8);
				} catch (UnsupportedEncodingException e) {
				}
				switch (trade.getType()) {
				case tradeOrderType.TYPE_ZHIHUI:case tradeOrderType.TYPE_MINSU:case tradeOrderType.TYPE_YOUHUI:
					return "redirect:/mallresult/success.htm?type=" + MallResultController.TRADE_TYPE + "&mallId=" + trade.getMallId()
							+ "&mallName=" + mallName+"&price="+trade.getPrice();
				case tradeOrderType.TYPE_MALLGROUPBUY:
					return "redirect:/mallresult/success.htm?type=" + MallResultController.TUAN_TRADE_TYPE + "&mallId=" + trade.getMallId()
							+ "&mallName=" + mallName+"&price="+trade.getPrice()+"&tuancode="+payBizImpl.TuanCodeAll(trade);
				default:
					return "redirect:/item/success.htm?tradeId=" + trade.getId();
					
				}
				
				

			} else {
				// TODO 用户取消支付宝订单或付款失败，这里最好是跳转到订单列表页
				response.getWriter().println("pay failed");
			}

			// 进入支付成功页面
		} else {
			// 进入支付失败页
			log.error("return_url参数校验失败");
		}

		return null;
	}

	
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		RETURN_URL = propertiesConfigure.getProperties(PropertiesKey.httpbeginurl) + "/aliPay/return_url.htm";
		NOTIFY_URL = propertiesConfigure.getProperties(PropertiesKey.httpbeginurl) + "/aliPay/notify_url.htm";
	}

}
